package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.FreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;

/**
 * @author Du leilei
 * @version 1.0
 * @Description
 * @createTime 2023年09月10日 21:33:00
 */
@Service
public class FreemarkerServiceImpl implements FreemarkerService {

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;
    /**
     * 文章详情页
     *
     * @param articleId
     * @param content
     */
    @Async
    @Override
    public void buildArticlePage(Long articleId, String content) {
        try {
            //1.准备数据
            HashMap<String, Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content));
            //2.拿到模板
            Template template = configuration.getTemplate("article.ftl");
            //3.将数据填到模板
            StringWriter sw = new StringWriter();
            template.process(map,sw);

            //4.上传至minio
            InputStream is = new ByteArrayInputStream(sw.toString().getBytes());
            String path = fileStorageService.uploadHtmlFile("", articleId+"html", is);

            //将minio的详情地址回填到ap_article表的static_url
            ApArticle apArticle = new ApArticle();
            apArticle.setId(articleId);
            apArticle.setStaticUrl(path);
            apArticleMapper.updateById(apArticle);
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
    }
}
